export default class RestfulApi {
    baseUrl: string
    constructor(baseUrl: string) {
        this.baseUrl = baseUrl
    }

    async request(endpoint: string, method = 'GET', data = null) {
        const url = `${this.baseUrl}\\${endpoint}`;
        let options: RequestInit | undefined
        if (method === 'GET' || method === 'HEAD ') {
            options = {
                method, 
                headers: { 'Content-Type': 'application/json' }
            }
        } else {
            options = {
                method,
                body: data ? JSON.stringify(data) : undefined,
                headers: { 'Content-Type': 'application/json' }
            }
        }
        const response = await fetch(url, options);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    }

    get(endpoint: string) {
        return this.request(endpoint);
    }

    post(endpoint: string, data: null | undefined) {
        return this.request(endpoint, 'POST', data);
    }
}